package com.aaa.controller;

import cn.hutool.core.io.IoUtil;
import com.aaa.entity.OssEntity;
import com.aaa.entity.Result;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * @author ：张恒（1371745897@qq.com）
 * @date ：Created in 2022/8/27 16:51
 * @description：
 * @modified By：
 * @version:
 */
@RestController
public class FileController extends BaseController {
    @Autowired
    OssEntity ossEntity;

    @PostMapping("upload.do")
    public Result upload(MultipartFile file) {
        //获取原始文件名
        String filename = file.getOriginalFilename();
        OSS ossClient = new OSSClientBuilder().build(ossEntity.getEndpoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());
        String newFileName = UUID.randomUUID() + filename;
        try {
            ossClient.putObject(ossEntity.getBucketName(), newFileName, new ByteArrayInputStream(file.getBytes()));
            String url = "http://" + ossEntity.getBucketName() + "." + ossEntity.getEndpoint() + "/" + newFileName;
            return success(url);
        } catch (IOException e) {
            e.printStackTrace();
            return fail();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

    }
}